package com.dd.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dd.common.constans.RedisFileKey;
import com.dd.mapper.UserFoldFileMapper;
import com.dd.pojo.entry.UserFoldFile;
import com.dd.service.RecycleService;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class RecycleServiceImpl implements RecycleService {
    private  final RedisTemplate<String,Object> redisTemplate;
    private  final UserFoldFileMapper userFoldFileMapper;


    /**
     * 显示回收站文件
     * @param userId
     * @return
     */
    @Override
    public List<UserFoldFile> findRecycleFile(String userId) {

        List<Object> values =redisTemplate.opsForHash().values(RedisFileKey.PREFIX_RECYCLE + userId);
        List<UserFoldFile> list = new ArrayList<>();
        if(!Collections.isEmpty(values)){
            for(Object data:values){
                JSONObject jsonObject = JSONUtil.parseObj(data);
                UserFoldFile file = JSONUtil.toBean(jsonObject, UserFoldFile.class);
                list.add(file);
            }
        }
        return list;
    }

    /**
     * 恢复回收站文件
     * @param fileMd5
     * @param userId
     */
    @Override
    public void ReRecycleFile(String fileMd5 ,String userId) {
       Object data = redisTemplate.opsForHash().get(RedisFileKey.PREFIX_RECYCLE + userId,fileMd5);


       if(Objects.nonNull(data)){
          UserFoldFile file = JSONUtil.parse(data).toBean(UserFoldFile.class);
          userFoldFileMapper.insert(file);
          redisTemplate.opsForHash().delete(RedisFileKey.PREFIX_RECYCLE + userId,fileMd5);

       }

    }

    /**
     * 删除回收站文件
     * @param fileMd5
     * @param userId
     */
    @Override
    public void DelRecycleFile(String fileMd5, String userId) {
        redisTemplate.opsForHash().delete(RedisFileKey.PREFIX_RECYCLE + userId,fileMd5);
    }


}
